package com.netdisk.demo.security;

import com.netdisk.demo.entity.Authorities;
import com.netdisk.demo.entity.User;
import com.netdisk.demo.service.AuthoritiesService;
import com.netdisk.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
 * @Author Wang
 * @Description Security 用户身份验证接口
 * @Date 22:28 2020/5/10
 **/

@Component
public class MyCustomUserService implements UserDetailsService {

    @Autowired
    private UserService userService;//引入用户服务类
    @Autowired
    private AuthoritiesService authoritiesService;//引入权限服务类
    /**
     * @author Wang
     * @description //TODO
     * @date 15:42 2020/5/14
     * @param username 用户名
     * @return org.springframework.security.core.userdetails.UserDetails
     **/
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MyUserDetails myUserDetails = new MyUserDetails();
        User user=userService.queryById(username);//通过用户名查询用户信息，并新建user对象
        if(user==null){
            throw new RuntimeException("用户不存在");
        }//判断数据库中是否存在此用户，前端已经避免输入为空，故在此不做检测
        myUserDetails.setUserName(username);//导入用户名
        myUserDetails.setPassword(user.getPassword());//导入密码
        myUserDetails.setAuthorities(getAuthority(username));//导入权限
        System.out.println("用户尝试登录"+'\n'
                +"          "+"用户名："+username+'\n'
                +"          "+"密码:"+myUserDetails.getPassword()+'\n'
                +"          "+"权限:"+myUserDetails.getAuthorities());
        return myUserDetails;
    }

    private Collection<GrantedAuthority> getAuthority(String username){
        List<GrantedAuthority> authorityList = new ArrayList<GrantedAuthority>();

        authorityList.add(
                new SimpleGrantedAuthority(
                        "ROLE_"+this.authoritiesService.queryById(username).getAuthority()//ROLE_admin
                )
        );//通过username从authorities表中查询其权限
        return  authorityList;
    }
}
